﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace StringBuilderTool
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private string FormatSql(string[] lines)
        {
            string res = string.Empty;

            try
            {
                StringBuilder sb = new StringBuilder();
                foreach (string sql in lines)
                {
                    sb.Append(sql);
                }
                res = Regex.Replace(sb.ToString(), @"[\s]+", " ");//将多个空格替换成一个空格,并大写
                if (chkSqlUpper.Checked)
                {
                    res = res.ToUpper();
                }
                else
                {
                    res = res.ToLower();
                }

                foreach (string keyword in _Keywords)
                {

                    string kw = keyword;
                    if (chkKeywordUpper.Checked)
                    {
                        kw = keyword.ToUpper();
                    }
                    else
                    {
                        kw = keyword.ToLower();
                    }
                    res = res.Replace(keyword.ToUpper(), string.Format("\r\n{0}", kw));

                    res = res.Replace(keyword.ToLower(), string.Format("\r\n{0}", kw));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return res;
        }


        private List<string> _Keywords = new List<string>() 
        {
            "SELECT",
            "FROM",
            "LEFT JOIN",
            "RIGHT JOIN",
            "CROSS JOIN",
            "OUTTER JOIN",
            "WHERE",
            "AND",
            "ORDER BY",
            "GROUP BY",
            "EXISTS",
            "WITH(NOLOCK)",
            "WITH",
            "AS",
            "OVER"
        };


        private void btnGenerate_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtName.Text))
                {
                    MessageBox.Show("请输入变量名啦。");
                    return;
                }
                if (string.IsNullOrEmpty(txtSQL.Text))
                {
                    MessageBox.Show("请输入SQL语句啦。");
                    return;
                }

                string name = txtName.Text;//变量名
                bool isFormat = chkFormat.Checked;
                bool isAutoPad = chkAutoPad.Checked;
                StringBuilder sb = new StringBuilder();
                sb.Append(string.Format("StringBuilder {0} = new StringBuilder();\r\n", name));

                int lineMaxLength = txtSQL.Lines.Select(m => new KeyValuePair<string, int>(m, m.Length)).OrderByDescending(m => m.Value).FirstOrDefault().Value;
                foreach (string sql in txtSQL.Lines)
                {
                    if (!string.IsNullOrEmpty(sql) && sql.Trim().Length > 0)
                    {
                        string sqlStr = sql.Trim();
                        int noteIndex = sqlStr.IndexOf("--");
                        string note = string.Empty;
                        if (noteIndex > -1)
                        {
                            note = sqlStr.Substring(noteIndex);
                            note = note.Replace("--", " //");
                            sqlStr = sql.Substring(0, noteIndex);

                        }
                        if (isAutoPad)
                        {
                            sqlStr = string.Format("\t{0}", sqlStr.PadRight(lineMaxLength, ' '));
                        }
                        if (isFormat)
                        {
                            sb.Append(string.Format("{0}.AppendFormat(\" {1} \");{2}\r\n", name, sqlStr, note));
                        }
                        else
                        {
                            sb.Append(string.Format("{0}.Append(\" {1} \");{2}\r\n", name, sqlStr, note));
                        }
                    }
                }

                txtCs.Text = sb.ToString();
                txtCs.SelectAll();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnReback_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtName.Text))
                {
                    MessageBox.Show("请输入变量名啦。");
                    return;
                }
                if (string.IsNullOrEmpty(txtCs.Text))
                {
                    MessageBox.Show("请输入SQL语句啦。");
                    return;
                }
                bool isFormat = chkFormat.Checked;
                string name = txtName.Text;//变量名

                StringBuilder sb = new StringBuilder();
                foreach (string sql in txtCs.Lines)
                {
                    string forward = string.Empty;
                    if (isFormat)
                    {
                        forward = string.Format("{0}.AppendFormat(\"", name);
                    }
                    else
                    {
                        forward = string.Format("{0}.Append(\"", name);
                    }

                    string back = "\");";
                    string s = sql.Trim();
                    s = s.Replace(forward, "");
                    s = s.Replace(back, "");
                    s = s.Replace("//", "--");
                    sb.Append(s + "\r\n");
                }

                txtSQL.Text = sb.ToString();
                txtSQL.SelectAll();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnAbout_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("\r使用方法\r\n");
            sb.Append("1.生成：\r\n");
            sb.Append(" 输入变量名，输入SQL语句，点击生成按钮，即可生成StringBuilder的字符串\r\n");
            sb.Append("2.还原：\r\n");
            sb.Append(" 输入变量名，输入C#代码，点击还原按钮，即可还原成SQL语句的字符串\r\n");
            sb.Append("3.格式化SQL：\r\n");
            sb.Append(" 输入sql语句，点击格式化按钮，即可简易格式化sql语句。\r\n");
            sb.Append(" 作者：谭旭贤 2014/1/3\r\n");
            sb.Append(" 2014/5/6 更新 区分注释\r\n");
            sb.Append(" 2014/8/5 更新 格式化按钮\r\n");
            sb.Append(" 2014/9/2 更新 关键字大小写选项\r\n");
            sb.Append(" 2015/12/15 更新 自动补全一行选项\r\n");

            MessageBox.Show(sb.ToString());
        }

        private void txtSQL_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
            {
                ((TextBox)sender).SelectAll();
            }
        }

        private void btnFormatSql_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtSQL.Text))
            {
                MessageBox.Show("请输入SQL语句啦。");
                return;
            }
            string str = FormatSql(txtSQL.Lines);
            txtSQL.Text = str;
        }


    }
}
